<template>
    <view class="user-profile-page safe-container">
        <!-- 状态栏安全区域 -->
        <view class="status-bar-safe-area" :style="{ height: statusBarHeight + 'px' }"></view>

        <!-- 用户信息区域 -->
        <view class="user-info-section">
            <view class="user-avatar-container">
                <image :src="userInfo.avatarUrl || '/static/images/default-avatar.png'" mode="aspectFill"
                    class="user-avatar"></image>
            </view>
            <view class="user-details">
                <view class="user-name">{{ userInfo.nickName || '未知用户' }}</view>
                <view class="user-gender">
                    <text v-if="userInfo.gender === 1" class="gender-icon male">♂</text>
                    <text v-else-if="userInfo.gender === 2" class="gender-icon female">♀</text>
                    <text v-else class="gender-icon unknown">👽</text>
                </view>
            </view>
        </view>

        <!-- 操作按钮 -->
        <view class="action-buttons">
            <button class="action-btn add-friend-btn" @tap="addFriend" :disabled="isFriendRequestSent || isAlreadyFriend || friendStatus !== 0">{{ 
                getFriendButtonText()
            }}</button>
            <button class="action-btn chat-btn" @tap="startChat">私聊</button>
        </view>

        <!-- 用户帖子 -->
        <view class="user-posts-section">
            <view class="section-title">发布的帖子</view>
            <view class="post-list" v-if="userPosts.length > 0">
                <view class="post-card" v-for="(post, index) in userPosts" :key="index" @tap="openPostDetail(post)">
                    <view class="post-title">{{ post.title }}</view>
                    <view class="post-time">{{ post.createTime }}</view>
                </view>
            </view>
            <view class="no-posts" v-else>
                该用户暂无发布帖子
            </view>
        </view>
    </view>
</template>

<script setup>
    import {
        ref,
        onMounted
    } from 'vue'
    import {
        onLoad
    } from '@dcloudio/uni-app'
    import systemUtils from '../../common/utils/system.js'
    import userManager from '../../common/utils/user.js'
    import {
        UserProfileInfo
    } from '@/api/userProfile.js'
    import {
        addFriend as addFriendApi,
        getAllFriends
    } from '@/api/friend.js'
    import {
        sendSocketMessage
    } from '@/common/utils/websocket.js'
    import messageCenter from '@/common/utils/messagecenter.js'

    const statusBarHeight = ref(0)
    const userInfo = ref({})
    const userId = ref('')
    const userPosts = ref([])
    const isFriendRequestSent = ref(false) // 是否已发送好友申请
    const isAlreadyFriend = ref(false) // 是否已经是好友
    const friendStatus = ref(0) // 好友关系状态: 0-无关系, 1-已是好友, 2-已拒绝, 4-被拒绝

    onLoad(async (options) => {
        statusBarHeight.value = systemUtils.getStatusBarHeight()

        if (options.userId) {
            userId.value = options.userId
            // 获取用户信息
            try {
                const user = await UserProfileInfo.getUserInfo(options.userId)
                if (user) {
                    userInfo.value = user
                    console.log('用户信息:', userInfo.value)
                }
            } catch (error) {
                console.error('获取用户信息失败:', error)
                uni.showToast({
                    title: '获取用户信息失败',
                    icon: 'none'
                })
            }
            // 获取用户帖子
            try {
                const posts = await UserProfileInfo.getPostByUserId(options.userId)
                if (posts) {
                    userPosts.value = posts
                }
            } catch (error) {
                console.error('获取用户帖子失败:', error)
                uni.showToast({
                    title: '获取用户帖子失败',
                    icon: 'none'
                })
            }
            
            // 检查好友状态
            checkFriendStatus()
        } else {
            uni.showToast({
                title: '用户信息错误',
                icon: 'none'
            })
            setTimeout(() => {
                uni.navigateBack()
            }, 1000)
        }
    })

    // 检查好友状态
    const checkFriendStatus = async () => {
        // 获取当前登录用户信息
        const currentUser = userManager.getUserInfo()
        if (!currentUser || !currentUser.userId) return

        // 调用后端API检查好友关系状态
        try {
            const res = await getAllFriends(currentUser.userId)
            if (res.data.code === 200) {
                const friends = res.data.data || []
                const friend = friends.find(f => f.friendUserId == userId.value)
                
                if (friend) {
                    // 根据friendStatus设置状态
                    friendStatus.value = friend.friendStatus
                    isAlreadyFriend.value = friend.friendStatus === 1
                    isFriendRequestSent.value = friend.friendStatus === 0
                } else {
                    // 没有找到好友关系
                    friendStatus.value = 0
                    isAlreadyFriend.value = false
                    isFriendRequestSent.value = false
                }
            }
        } catch (error) {
            console.error('检查好友状态失败:', error)
            // 出错时使用本地存储作为备选方案
            const friends = uni.getStorageSync('friends') || []
            isAlreadyFriend.value = friends.includes(userId.value)
            
            // 检查是否已发送好友申请
            const friendRequests = uni.getStorageSync('friendRequests') || []
            isFriendRequestSent.value = friendRequests.includes(userId.value)
        }
    }

    // 获取好友按钮文本
    const getFriendButtonText = () => {
        if (isAlreadyFriend.value) {
            return '已是好友'
        } else if (isFriendRequestSent.value) {
            return '已发送申请'
        } else if (friendStatus.value === 2 || friendStatus.value === 4) {
            return '已被拒绝'
        } else {
            return '添加好友'
        }
    }

    const addFriend = async () => {
        // 检查是否已登录
        if (!userManager.checkLogin()) {
            uni.showToast({
                title: '请先登录',
                icon: 'none'
            })
            setTimeout(() => {
                uni.switchTab({
                    url: '/pages/mine/mine'
                })
            }, 1000)
            return
        }

        // 获取当前登录用户信息
        const currentUser = userManager.getUserInfo()
        
        // 检查是否是自己
        if (currentUser && currentUser.userId == userInfo.value.userId) {
            uni.showToast({
                title: '不能添加自己为好友',
                icon: 'none'
            })
            return
        }
        
        // 检查是否已经是好友
        if (isAlreadyFriend.value) {
            uni.showToast({
                title: '你们已经是好友了',
                icon: 'none'
            })
            return
        }
        
        // 检查是否已发送申请
        if (isFriendRequestSent.value) {
            uni.showToast({
                title: '已发送好友申请，请等待对方同意',
                icon: 'none'
            })
            return
        }

        try {
            // 调用后端API发送好友申请
            const result = await addFriendApi(currentUser.userId, userId.value)
            
            if (result.data.code === 200) {
                uni.showToast({
                    title: '好友申请已发送',
                    icon: 'success'
                })
                
                // 标记已发送申请
                isFriendRequestSent.value = true
                friendStatus.value = 0 // 待确认状态
                
                // 保存到本地存储（模拟）
                const friendRequests = uni.getStorageSync('friendRequests') || []
                friendRequests.push(userId.value)
                uni.setStorageSync('friendRequests', friendRequests)
                
                // 通过WebSocket发送好友申请通知给对方
                const message = {
                    id: 'friend_request_' + Date.now(),
                    fromId: currentUser.userId,
                    toId: userId.value,
                    name: currentUser.nickName || '未知用户',
                    headImg: currentUser.avatarUrl || '/static/images/default-avatar.png',
                    msg: `${currentUser.nickName || '用户'} 请求添加您为好友`,
                    time: new Date().toLocaleString(),
                    type: 'send',
                    messageType: 'notification', // 指定为提醒类型消息
                    action: 'friend_request', // 操作类型
                    data: {
                        requesterId: currentUser.userId,
                        requesterName: currentUser.nickName,
                        requesterAvatar: currentUser.avatarUrl
                    }
                }
                
                // 发送WebSocket消息
                await sendSocketMessage(message)
                
                // 同时在本地创建一个提醒消息
                messageCenter.saveMessage(message)
            } else {
                uni.showToast({
                    title: result.data.message || '发送好友申请失败',
                    icon: 'none'
                })
            }
        } catch (error) {
            console.error('发送好友申请失败:', error)
            uni.showToast({
                title: '发送好友申请失败',
                icon: 'none'
            })
        }
    }

    const startChat = () => {
        // 检查是否已登录
        if (!userManager.checkLogin()) {
            uni.showToast({
                title: '请先登录',
                icon: 'none'
            })
            setTimeout(() => {
                uni.switchTab({
                    url: '/pages/mine/mine'
                })
            }, 1000)
            return
        }

        // 获取当前登录用户信息
        const currentUser = userManager.getUserInfo();
        
        // 检查是否是自己
        if (currentUser && currentUser.userId == userInfo.value.userId) {
            uni.showToast({
                title: '不能和自己聊天',
                icon: 'none'
            })
            return
        }
        // 跳转到聊天页面，传递目标用户信息
        uni.navigateTo({
            url: `/pages/chat/chat?id=${userId.value}&chatType=friend&name=${encodeURIComponent(userInfo.value.nickName || '未知用户')}&avatar=${encodeURIComponent(userInfo.value.avatarUrl || '/static/images/default-avatar.png')}`
        })
    }

    const openPostDetail = (post) => {
        uni.navigateTo({
            url: `/pages/post-detail/post-detail?id=${post.postId}`
        })
    }
</script>

<style scoped>
    @import url('./user-profile.css');
</style>